package routers

import (
	"encoding/json"
	"net/http"

	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/popedom"
	"shqsoft.cn/pas3ui/popedom/entity"

	jwt "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

//ChangePassword 修改用户密码
func ChangePassword(c echo.Context) error {
	oldPwd := c.FormValue("OldPassword")
	if oldPwd == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "OldPassword不能为空！")
	}
	newPwd := c.FormValue("NewPassword")
	if newPwd == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "rolePerms不能为空！")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	err := popedom.ModifyPassword(claims.UserID, oldPwd, newPwd)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	base.LogToDB(claims.UserID, 140, "修改密码", c.RealIP())
	return c.JSON(http.StatusOK, "ok")
}

//InitializePassword 初始化用户密码
func InitializePassword(c echo.Context) error {
	var userIDs []int
	jsonStr := c.FormValue("UserIDs")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "UserIDs不能为空！")
	}
	err := json.Unmarshal([]byte(jsonStr), &userIDs)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(userIDs); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "userIDs不能为空数组！")
	}
	for _, uID := range userIDs {
		err = popedom.InintPassword(uID)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	base.LogToDB(claims.UserID, 140, "初始化密码", c.RealIP())
	return c.JSON(http.StatusOK, "ok")
}

//LeaveOffice 初始化用户密码
func LeaveOffice(c echo.Context) error {
	var userIDs []int
	jsonStr := c.FormValue("UserIDs")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "UserIDs不能为空！")
	}
	err := json.Unmarshal([]byte(jsonStr), &userIDs)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(userIDs); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "userIDs不能为空数组！")
	}
	strSql := `update "T_SysUser" set "Password" ='password',"STATUS" ='2' where "ID" in (?)`
	err = base.MYDB.Exec(strSql, userIDs).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, "ok")
}

func InitializePasswordAll(c echo.Context) error {
	var pass []string
	user := entity.SysUser{}
	err := base.MYDB.Model(&user).Where(`"ID"<>0`).Pluck("SysUserID", &pass).Error
	if err != nil {
		return err
	}
	for _, v := range pass {
		nPwd := popedom.HashPassword(v, "00000000")
		err = base.MYDB.Model(&user).Where(`"SysUserID"=?`, v).Update("Password", nPwd).Error
		if err != nil {
			return err
		}
	}
	return c.JSON(http.StatusOK, "ok")
}
